<template>
  <div class="app-main-plus container">

    <!--头部操作-->
    <div class="header-box">
      <div class="left">
        <el-button type="primary" size="small" icon="el-icon-arrow-left" plain @click="goBack">返回</el-button>
      </div>
      <div class="right">
        <!--<el-button type="primary" size="small" :disabled="editable" @click="handleSave">暂存</el-button>-->
        <el-button type="primary" size="small" v-if="!editable" @click="handleSave">提交</el-button>
        <!--<el-button type="primary" size="small" :disabled="editable" @click="handleSave">提交</el-button>-->
      </div>
    </div>
    <!--头部操作-->

    <div class="content-container" style="padding: 10px">

      <!--基本信息-->
      <formtitle title="基本信息">
        <div class="context-warp">
          <div class="page-form-item">
            <label class="page-form-item-label">
              <span class="page-form-item-label__text"><i class="icon" style="margin-right: 4px;">*</i>项目名称</span>
            </label>
            <div class="page-form-item-content">
              <zb-form-select-data v-bind="option" v-model="baseData.projectName" :disabled="editable" @dataChange></zb-form-select-data>
            </div>
          </div>

          <div class="page-form-item">
            <label class="page-form-item-label">
              <span class="page-form-item-label__text">项目编码</span>
            </label>
            <div class="page-form-item-content">
              <el-input v-model.trim="baseData.projectNumber" disabled></el-input>
            </div>
          </div>

          <div class="page-form-item">
            <label class="page-form-item-label">
              流程标题
            </label>
            <div class="page-form-item-content">
              {{baseData.projectName+'结算编制'+baseData.createTime}}
            </div>
          </div>

          <div class="page-form-item">
            <label class="page-form-item-label">
              <span class="page-form-item-label__text">猪场名称</span>
            </label>
            <div class="page-form-item-content">
              <el-input v-model.trim="baseData.pigfarmName" disabled></el-input>
            </div>
          </div>

          <div class="page-form-item">
            <label class="page-form-item-label">
              <span class="page-form-item-label__text"><i class="icon" style="margin-right: 4px;">*</i>合同名称</span>
            </label>
            <div class="page-form-item-content">
              <el-select v-model="baseData.contractTitle" :disabled="editable" clearable filterable @change="handleContractChange">
                <el-option :label="item.contractTitle" :value="item.id" :key="item.id" v-for="item in contractList"></el-option>
              </el-select>
            </div>
          </div>

          <div class="page-form-item">
            <label class="page-form-item-label">
              <span class="page-form-item-label__text"><i class="icon" style="margin-right: 4px;">*</i>承建单位</span>
            </label>
            <div class="page-form-item-content">
              <el-input v-model.trim="baseData.supplierName" maxLength="30" disabled></el-input>
            </div>
          </div>

          <div class="page-form-item">
            <label class="page-form-item-label">
              <span class="page-form-item-label__text">合同金额(元)</span>
            </label>
            <div class="page-form-item-content">
              <el-input type="number" v-model.trim="baseData.contractMoney" disabled></el-input>
            </div>
          </div>

          <div class="page-form-item">
            <label class="page-form-item-label">
              <span class="page-form-item-label__text"><i class="icon" style="margin-right: 4px;">*</i>结算金额(元)</span>
            </label>
            <div class="page-form-item-content">
              <el-input type="number" v-model.trim="baseData.balanceMoney" :min="0" :disabled="editable"
                        @blur="handleBlur"
                        onKeypress="return (/[\d\.]/.test(String.fromCharCode(event.keyCode)))"></el-input>
            </div>
          </div>



          <div class="page-form-item" style="width: 100%;height: 100px;">
            <label class="page-form-item-label">
              <span class="page-form-item-label__text"><i class="icon" style="margin-right: 4px;">*</i>摘要信息</span>
            </label>
            <div class="page-form-item-content">
              <el-input v-model.trim="baseData.remark" type="textarea" maxLength="128" :disabled="editable"></el-input>
            </div>
          </div>

          <div class="page-form-item">
            <label class="page-form-item-label">
              <span class="page-form-item-label__text">申请人</span>
            </label>
            <div class="page-form-item-content">
              <el-input v-model.trim="baseData.createName" disabled></el-input>
            </div>
          </div>

          <div class="page-form-item">
            <label class="page-form-item-label">
              <span class="page-form-item-label__text">申请时间</span>
            </label>
            <div class="page-form-item-content">
              <el-date-picker v-model="baseData.createTime" type="date" placeholder="选择日期" disabled></el-date-picker>
            </div>
          </div>

          <div class="page-form-item">
            <label class="page-form-item-label"></label>
            <div class="page-form-item-content"></div>
          </div>
        </div>
      </formtitle>
      <!--基本信息-->


      <!--      竣工验收资料 start-->
      <formtitle title="竣工验收资料" :hideCollapse="false" :default-open="false">
        <zb-form
          v-bind="formOptions"
          :model="baseData.completeInfoVo"
          v-loading="loading"
          ref="form1">
        </zb-form>
      </formtitle>
      <!--      竣工验收资料 end-->

      <!--结算资料列表-->
      <formtitle title="结算资料">
        <el-table ref="elTable" :data="list" size="small" stripe height="300" border>
          <el-table-column type="index" label="序号" width="55"></el-table-column>
          <el-table-column prop="name" label="资料名称">
            <template slot-scope="scope">
              <span>技改结算文件</span>
            </template>
          </el-table-column>
          <el-table-column label="资料名称">
            <template slot-scope="scope">
              <div style="display: flex">
                <file-upload :fileList="scope.row.balanceFiles" :disabled="editable" @handleUploadSuccess="(file) => handleUploadSuccess(file)"
                             @handleFileRemove="(file) => handleFileRemove(file)" ></file-upload>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createBy" label="上传人" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createTime" label="上传时间" show-overflow-tooltip></el-table-column>
        </el-table>
      </formtitle>
      <!--结算资料列表-->


      <!--预算流程列表-->
      <formtitle title="关联预算流程">
        <el-table ref="multipleTable" :data="baseData.bpmInfos" size="small" stripe height="300" border @selection-change="handleSelectedFlowChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="55"></el-table-column>
          <el-table-column prop="bpmTitle" label="流程名称"></el-table-column>
          <el-table-column prop="createBy" label="流程发起人" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createTime" label="流程发起时间" show-overflow-tooltip></el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-button @click.native.prevent="handleApproveCheck(scope.row.instId)" type="text" size="small">审批查询</el-button>
            </template>
          </el-table-column>
        </el-table>
      </formtitle>
      <!--预算流程列表-->

    </div>
  </div>
</template>

<script>
  import card from "@/components/Card/index";
  import fileUpload from '@/views/components/fileUpload/index.vue'
  import { getDetailInfoApi, getContractListApi, getBudgetFlowListApi, addAndUpdateApi } from '@/api/settleManage/settleCompile'
  import { getCurrentDate } from "@/utils/dateUtils";
  import { newWindowBpm } from "@/utils/openBpm";
  import Index from "./index";
  import {getToken} from "@/utils/auth";
  import BaseIndex from "@/views/base/BaseIndex";
  import Formtitle from "@/views/components/FormTitle";


  export default {
    name: "settleCompileDetail",
    components:{Formtitle, card, fileUpload },
    extends:BaseIndex,
    data(){
      return {
        editable:false,//是否可编辑

        option:{
          label: "项目名称",
          prop: "projectName",
          type: "selectData",
          searchKey: "projectName",
          span: 8,
          url: `${process.env.VUE_APP_BASE_API}/pigfarm-project/like`,
          props: {
            label: "projectName",
            value: "projectId"
          },
          createdRequest: false,
          searchIconVisible:true,
          filterAble:false,
          selectAble: true,
          getDictSuccessStatus:0,
          getDictResultMap:{
            status:'data.code',
            data:'data.data',
            list:'data.data.records',
            total:'data.data.total',
          },
          dialogType:2,
          labelFields:['pigfarmName','pigfarmNumber','projectName','projectNumber'],
          labelFieldsName:['猪场名称','猪场编号','项目名称','项目编号'],
          searchLabel:['projectName'],
          searchLabelName:['项目名称'],
          headers:{
            Authorization:'Bearer '+getToken()
          },
          listeners: {
            dataChange: val => {
              if (val){
                const { pigfarmId, pigfarmName, pigfarmNumber, projectId,projectName, projectNumber } = val;
                //debugger
                this.$set(this.baseData,'projectId',projectId)
                this.$set(this.baseData,'projectName',projectName)
                this.$set(this.baseData,'projectNumber',projectNumber)
                this.$set(this.baseData,'pigfarmId',pigfarmId)
                this.$set(this.baseData,'pigfarmNumber',pigfarmNumber)
                this.$set(this.baseData,'pigfarmName',pigfarmName)
                this.$set(this.baseData,'contractTitle','')//重置合同
                this.$set(this.baseData,'leCode','')//重置承建单位
                this.$set(this.baseData,'supplierName','')//重置承建单位
                this.$set(this.baseData,'contractMoney','')//重置合同金额
                this.getContractList(projectId,this.baseData.contractTitle);
                this.getBudgetFlowList(projectId);
              }
            }
          }
        },
        baseData:{
          projectId: "",
          projectName: "",
          projectNumber: "",
          pigfarmId: "",
          pigfarmName: "",
          pigfarmNumber: "",
          contractId:"",
          contractTitle:"",
          leCode:"",
          supplierName:"",
          contractMoney:"",
          balanceMoney:"",
          remark:"",
          createName:this.$store.getters.account,
          createTime:getCurrentDate(),
          balanceFiles: [],//结算资料列表
          bpmInfos:[],//关联预算流程列表(用于详情回显)
          refInstIds:[],//关联预算流程列表id(用于新增编辑提交接口)
          completeInfoVo:{}
        },
        formOptions:{
          labelWidth: "160px",
          rules: {
          },
          options: [
            {
              label: "竣工验收会议纪要",
              prop: "meetingFiles",
              type: 'file',
              span: 24,
              disabled:true,
              height:90,
              url:`${process.env.VUE_APP_BASE_API}/file/upload`,
              downUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              previewUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              headers:{
                Authorization:'Bearer '+getToken()
              },
              resultDataMap:{
                fileName:'',
                filePath:'',
              }
            },
            {
              label: "验收报告",
              prop: "checkFiles",
              type: 'file',
              span: 24,
              disabled:true,
              height:90,
              url:`${process.env.VUE_APP_BASE_API}/file/upload`,
              downUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              previewUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              headers:{
                Authorization:'Bearer '+getToken()
              },
              resultDataMap:{
                fileName:'',
                filePath:'',
              }
            },
            {
              label: "整改报告",
              prop: "reformFiles",
              type: 'file',
              span: 24,
              disabled:true,
              height:90,
              url:`${process.env.VUE_APP_BASE_API}/file/upload`,
              downUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              previewUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              headers:{
                Authorization:'Bearer '+getToken()
              },
              resultDataMap:{
                fileName:'',
                filePath:'',
              }
            },
            {
              label: "影像资料",
              prop: "videoFiles",
              type: 'file',
              span: 24,
              disabled:true,
              height:90,
              url:`${process.env.VUE_APP_BASE_API}/file/upload`,
              downUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              previewUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              headers:{
                Authorization:'Bearer '+getToken()
              },
              resultDataMap:{
                fileName:'',
                filePath:'',
              }
            },
            {
              label: "其他附件",
              prop: "otherFiles",
              type: 'file',
              span: 24,
              disabled:true,
              height:90,
              url:`${process.env.VUE_APP_BASE_API}/file/upload`,
              downUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              previewUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              headers:{
                Authorization:'Bearer '+getToken()
              },
              resultDataMap:{
                fileName:'',
                filePath:'',
              }
            },
          ]
        },
        list:[{balanceFiles:[]}],//结算资料列表
        contractList:[],//合同列表
        selectedFlowList:[],//选中的关联流程
      }
    },

    created(){
      const { type, id } = this.$route.query;
      this.editable = type === 'view';
      if(id){
        this.getDetailInfo(id);
      }
    },
    methods:{

      /**
       * 获取详情
       */
      getDetailInfo(id){
        const loading = this.$loading({lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
        getDetailInfoApi(id).then(res => {
          console.log('详情:',res);
          loading.close();
          if(res.code === 0){
            // debugger
            this.baseData = res.data;
            let { status, balanceFiles } = res.data;
            //设置选中项
            this.$nextTick(() => {
              if(res.data.bpmInfos.length){
                res.data.bpmInfos.map((item,index) => {
                  if(item.flag===1){
                    this.toggleSelection([this.baseData.bpmInfos[index]]);
                  }
                })
              }
            })
            if(balanceFiles.length){
              balanceFiles.map(item => {
                item.name = item.fileName;
              });
              this.$set(this.list[0],'balanceFiles',balanceFiles);
              this.$set(this.list[0],'createBy',balanceFiles[0].createBy);
              this.$set(this.list[0],'createTime',balanceFiles[0].createTime);
            }

            if(this.$route.query.type==="view"){
              this.editable = true;
            }else{
              //设置编辑状态(暂存 || 退回、驳回 ||作废状态可编辑)
              if(!status || status === 'save' || status === 'reject' || status === 'cancel'){
                this.editable = false;
              }else{
                this.editable = true;
              }
            }
          }else{
            this.$message.warning(res.msg);
          }
        }).catch(error => {
          console.log('error:',error);
          loading.close();
        })
      },


      /**
       * 获取合同列表
       */
      getContractList(projectId,contractTitle){
        const loading = this.$loading({lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
        getContractListApi(projectId,contractTitle).then(res => {
          console.log('合同列表:',res);
          loading.close();
          if(res.code === 0){
            this.contractList = res.data;
          }else{
            this.$message.warning(res.msg);
          }
        }).catch(error => {
          console.log('error:',error);
          loading.close();
        })
      },

      /**
       * 获取预算流程列表
       */
      getBudgetFlowList(projectId){
        const loading = this.$loading({lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
        getBudgetFlowListApi('budget',projectId).then(res => {
          console.log('预算流程列表:',res);
          loading.close();
          if(res.code === 0){
            if(!res.data.length){
              this.$message.warning("该项目不存在关联预算流程!");
            }else{
              this.baseData.bpmInfos = res.data;
            }
          }else{
            this.$message.warning(res.msg);
          }
        }).catch(error => {
          console.log('error:',error);
          loading.close();
        })
      },


      /**
       *返回
       */
      goBack(){
        this.$router.go(-1)
        // this.$router.push({
        //   path:'/settleManage/settleCompile/index'

        // });
      },

      /**
       * 数据校验
       */
      checkData(){
        const { projectName, contractTitle, balanceMoney, remark } = this.baseData;
        //debugger
        if(!projectName){
          this.$message.warning("请选择项目!");
          return false;
        }else if(!contractTitle){
          this.$message.warning("请选择合同!");
          return false;
        }else if(balanceMoney===""){
          this.$message.warning("请填写结算金额!");
          return false;
        }else if(remark===""){
          this.$message.warning("请填写摘要信息!");
          return false;
        }else{
          const { balanceFiles } = this.list[0];
          if(!balanceFiles.length){
            this.$message.warning("结算资料列表不能为空!");
            return false;
          }else if(!this.selectedFlowList.length){
            this.$message.warning("请选择关联预算流程!");
            return false;
          }else{
            return true
          }
        }
      },

      /**
       * 提交
       */
      handleSave(){
        const status = this.checkData();
        if(status){
          const { type } = this.$route.query;
          console.log('baseData:',this.baseData);
          this.baseData.balanceFiles = this.list[0].balanceFiles;
          const loading = this.$loading({lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
          addAndUpdateApi(type,this.baseData).then(res => {
            console.log('新增:',res);
            loading.close();
            if(res.code === 0){
              this.$message.success("提交成功");
              newWindowBpm(res.data,true,{path:`/settleCompile/index`},true, Index);
            }else{
              this.$message.warning(res.msg);
            }
          }).catch(error => {
            console.log('error:',error);
            loading.close();
          })
        }
      },


      /**
       * 合同change事件
       */
      handleContractChange(val){
        const obj = this.contractList.find(item => {
          return item.id === val;
        });
        //debugger
        const { contractTitle, leCode, supplierName, contractMoney } = obj;
        this.baseData.contractId = val;
        this.baseData.contractTitle = contractTitle;
        this.baseData.leCode = leCode;
        this.baseData.supplierName = supplierName;
        this.baseData.contractMoney = contractMoney;
      },


      /**
       * 输入框框blue事件
       */
      handleBlur(){
        let { balanceMoney } = this.baseData;
        balanceMoney = parseFloat(balanceMoney).toFixed(2);
        if(balanceMoney>999999999999){
          this.$message.warning("最大值不得超出999999999999请重新输入");
          this.baseData.balanceMoney = null;
        }else{
          this.baseData.balanceMoney = balanceMoney;
        }
      },




      /**
       *文件上传成功
       */
      handleUploadSuccess(files){
        //debugger
        this.list[0].balanceFiles = files;
        if(files.length){
          const { createBy, createTime } = files[0];
          this.$set(this.list[0],'createBy',createBy);
          this.$set(this.list[0],'createTime',createTime);
        }
      },

      handleFileRemove(files){
        this.list[0].balanceFiles = files;
      },

      /**
       * 文件查看
       */
      checkFile(data){
        const { name, id } = data;
        const url = `/build/file/download/${id}`;
        window.open(url,'_blank');
      },



      /**
       *设置关联流程选中状态
       */
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },

      /**
       *关联流程复选框事件
       */
      handleSelectedFlowChange(val){
        //debugger
        this.selectedFlowList = val;
        let ids = [];
        if(this.selectedFlowList.length){
          this.selectedFlowList.map(item => {
            ids.push(item.instId);
          })
          //设置refInstIds,详情接口不返回refInstIds字段会覆盖data里面的baseData,重新设置一遍用于新增和编辑提交
          this.$set(this.baseData,'refInstIds',ids);
        }
        console.log("refInstIds:",this.baseData.refInstIds);
      },

      /**
       *关联预算流程--审批查询
       */
      handleApproveCheck(instId){
        newWindowBpm(instId,true,{path:`/settleCompile/index`},true, Index);
      }

    }
  }
</script>

<style scoped lang="scss">
  @import "../../../style/form"; //table样式
  .container {
    .header-box{
      display: flex;
      width: 100%;
      height: 60px;
      line-height: 60px;
      padding: 20px;
      box-sizing: border-box;
      .left{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 20%;
      }
      .right{
        display: flex;
        justify-content: flex-end;
        align-items: center;
        width: 80%;
      }
    }
    .tool-box{
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-bottom: 5px;
    }
  }
  ::v-deep .el-upload-list__item-name {
    color: #606266;
    display: block;
    margin-right: 40px;
    overflow: hidden;
    padding-left: 4px;
    width: 240px;
    text-overflow: ellipsis;
    transition: color .3s;
    white-space: normal;
    word-break: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
</style>
